package com.example.lib_mvp.httpUtil;

import android.text.TextUtils;

import com.example.lib_mvp.base.mvp.HttpCallback;
import com.tjf.lib_network.httpHelper.CallBackUtil;

import java.util.HashMap;

import okhttp3.Call;

public abstract class BaseHttp {

    public static CallBackUtil onCallBack(HttpCallback callback) {
        return new CallBackUtil.CallBackString() {
            public void onFailure(Call call, Exception e) {
                judgmentsFailure(call.request().url().toString(),
                        e.getLocalizedMessage(), callback);
            }

            @Override
            public void onResponse(Call call, String response) {
                judgmentsResponse(call.request().url().toString(),
                        response, callback);
            }
        };
    }

    /**
     * 解析数据进行判断
     *
     * @param response
     * @param callback
     */
    public static void judgmentsResponse(String url, String response, HttpCallback callback) {
        if (!TextUtils.isEmpty(response) && !"接口异常".equals(response)) {
            callback.onSuccess(url, response);
        } else {
            callback.onFailure(url, "接口异常");
        }
        callback.onComplete();
    }

    public static void judgmentsFailure(String url, String error, HttpCallback callback) {
        callback.onError(url, error);
        callback.onComplete();

    }


    /**
     * get请求，只有键值对参数
     * <p>
     * 接口地址字符串的拼接
     */
    public static String setUrlParams(String mUrl, HashMap<String, Object> mParamsMap) {
        if (mParamsMap != null) {
            mUrl = mUrl + "?";
            for (String key : mParamsMap.keySet()) {
                mUrl = mUrl + key + "=" + mParamsMap.get(key) + "&";
            }
            mUrl = mUrl.substring(0, mUrl.length() - 1);
        }
        return mUrl;
    }

    public static String encodeURL(String url) {
        return url.replace("%", "%25").replace("+", "%2B")
                .replace(" ", "%20").replace("/", "%2F")
                .replace("?", "%3F").replace("#", "%23")
                .replace("&", "%26").replace("=", "%3D")
                .replace(":", "%3A");
    }
}
